package newshop

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	"time"
)

const clientId = "5dc57cf6c48fa1285b"
const clientSecret = "768482f74e0fbfcb8fb41fbacc182ff1"
const grantId = 44154005

type AccessTokenResponse struct {
	Data struct {
		AccessToken string `json:"access_token"`
	} `json:"data"`
}

func GetAccessToken() string {
	client := &http.Client{}
	var data = strings.NewReader(fmt.Sprintf(`{"client_id": "%s","client_secret": "%s","authorize_type": "silent", "grant_id": %d,"refresh":false}`, clientId, clientSecret, grantId))
	req, err := http.NewRequest("POST", "https://open.youzanyun.com/auth/token", data)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("content-type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(resp.Body)
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// json格式解析
	var response AccessTokenResponse
	err = json.Unmarshal(bodyText, &response)
	if err != nil {
		log.Fatal(err)
	}

	// 提取access_token
	return response.Data.AccessToken
}

type CreateUserResponse struct {
	Success bool `json:"success"`
}

func CreateUserForShop(mobile string, accessToken string) bool { // JSON参数的示例内容
	// 创建一个URL值对象，用于存储查询参数
	values := url.Values{}

	// 将结构体中的字段添加到查询参数中
	values.Add("access_token", accessToken)
	values.Add("mobile", mobile)

	// 目标URL
	baseURL := "https://open.youzanyun.com/api/youzan.scrm.customer.create/3.0.0"

	// 将查询参数附加到URL
	reqURL, err := url.Parse(baseURL)
	if err != nil {
		log.Fatal(err)
	}
	reqURL.RawQuery = values.Encode()

	// 构建GET请求
	req, err := http.NewRequest("GET", reqURL.String(), nil)
	if err != nil {
		log.Fatal(err)
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	// 读取响应体
	bodyText, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// 打印响应体
	fmt.Printf("Response body: %s\n", bodyText)

	var response CreateUserResponse
	err = json.Unmarshal(bodyText, &response)
	if err != nil {
		log.Fatal(err)
	}
	return response.Success
}

type ShowUserInfoResponse struct {
	TraceID string `json:"trace_id"`
	Code    int    `json:"code"`
	Data    struct {
		LatestInfo struct {
			NickName string `json:"nick_name"`
			Avatar   string `json:"avatar"`
		} `json:"latest_info"`
		UserList []struct {
			PrimitiveInfo struct {
				Country      string    `json:"country"`
				UpdatedTime  time.Time `json:"updated_time"`
				CreatedTime  time.Time `json:"created_time"`
				Province     string    `json:"province"`
				PlatformType int       `json:"platform_type"`
				Gender       int       `json:"gender"`
				City         string    `json:"city"`
				NickName     string    `json:"nick_name"`
				YzOpenID     string    `json:"yz_open_id"`
				Avatar       string    `json:"avatar"`
			} `json:"primitive_info"`
			MobileInfo struct {
				Mobile string `json:"mobile"`
			} `json:"mobile_info"`
			WechatInfo struct {
				FollowTime   int64  `json:"follow_time"`
				UnfollowTime int64  `json:"unfollow_time"`
				IsFans       int    `json:"is_fans"`
				LastTalkTime int64  `json:"last_talk_time"`
				UnionID      string `json:"union_id"`
				WechatType   int    `json:"wechat_type"`
			} `json:"wechat_info"`
			PlatformInfo struct {
				WeixinOpenID string `json:"weixin_open_id"`
			} `json:"platform_info"`
		} `json:"user_list"`
	} `json:"data"`
	Success bool   `json:"success"`
	Message string `json:"message"`
}

func ShowUserInfo(mobile string, accessToken string) ShowUserInfoResponse {
	// 创建一个URL值对象，用于存储查询参数
	values := url.Values{}

	// 将结构体中的字段添加到查询参数中
	values.Add("access_token", accessToken)
	values.Add("mobile", mobile)

	// 目标URL
	baseURL := "https://open.youzanyun.com/api/youzan.users.info.query/1.0.0"

	// 将查询参数附加到URL
	reqURL, err := url.Parse(baseURL)
	if err != nil {
		log.Fatal(err)
	}
	reqURL.RawQuery = values.Encode()

	// 构建GET请求
	req, err := http.NewRequest("GET", reqURL.String(), nil)
	if err != nil {
		log.Fatal(err)
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	// 读取响应体
	bodyText, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// 打印响应体
	fmt.Printf("Response body: %s\n", bodyText)

	var response ShowUserInfoResponse
	err = json.Unmarshal(bodyText, &response)
	if err != nil {
		log.Fatal(err)
	}
	return response
}

type AddResponse struct {
	Code int `json:"code"`
	Data struct {
		IsSuccess string `json:"is_success"`
	} `json:"data"`
	Success bool   `json:"success"`
	Message string `json:"message"`
}

func AddJf(accessToken string, points int, accountId string) AddResponse {
	client := &http.Client{}
	var data = strings.NewReader(fmt.Sprintf(`{"access_token": "%s","points": %d,"reason":"社区志愿者小程序换取积分","account_type":3, "account_id": "%s"}`, accessToken, points, accountId))
	req, err := http.NewRequest("POST", "https://open.youzanyun.com/auth/token", data)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("content-type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(resp.Body)
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// json格式解析
	var response AddResponse
	err = json.Unmarshal(bodyText, &response)
	if err != nil {
		log.Fatal(err)
	}

	// 提取access_token
	return response
}
